package com.imti.xmlparserdemo;

import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParserException;

public class MainActivity extends AppCompatActivity
{

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try
        {
            initData();
        } catch (IOException | ParserConfigurationException | SAXException e)
        {
            e.printStackTrace();
        }

        try
        {
            List<StudentModel> result =
                PullParseUtil.parseStudentList(getAssets().open("student.xml"));

            for (int i = 0; i < result.size(); i++)
            {
                Log.d(TAG, " id " + result.get(i).getId() +
                               " 姓名：" + result.get(i).getName() +
                               " 年龄：" + result.get(i).getAge());
            }

        } catch (XmlPullParserException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private void initData() throws IOException, ParserConfigurationException, SAXException
    {
        InputStream is = getAssets().open("student.xml");

        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();

        SAXHelper helper = new SAXHelper();

        parser.parse(is, helper);

        List<StudentModel> result = helper.getDataList();
        for (int i = 0; i < result.size(); i++)
        {
            Log.d(TAG, " id " + result.get(i).getId() +
                           " 姓名：" + result.get(i).getName() +
                           " 年龄：" + result.get(i).getAge());
        }
    }
}